﻿using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using ImoviesBlazorAntPro.Shared.Dtos;
using System.Net.Http;
using Microsoft.AspNetCore.Components;
using AntDesign;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Components.Web;
using System.Net.Http.Json;

namespace ImoviesBlazorAntPro.Client.Pages.Admin
{
    public partial class AnimationManage
    {
        [Inject]
        HttpClient HttpClient { get; set; }
        [Inject]
        IMessageService MessageService { get; set; }
        [Inject]
        ModalService ModalService { get; set; }



        int _pageIndex = 1;
        int _pageSize = 10;
        int _total = 0;

        List<AnimationDto> dataList = new List<AnimationDto>();
        IEnumerable<AnimationDto> selectedRows;

        private class TempData
        {
            public List<AnimationDto> Data { get; set; } = new List<AnimationDto>();
            public int Total { get; set; }
        }

        /// <summary>
        /// 显示添加对话框
        /// </summary>
        private void ShowAddModal()
        {
            addModel.Name = string.Empty;
            addModel.Url = string.Empty;
            addModel.Category = string.Empty;
            addModel.Region = string.Empty;
            addModel.Director = string.Empty;
            addModel.Actors = string.Empty;
            addModel.Img = string.Empty;
            addModel.Intro = string.Empty;
            addModel.Comment = string.Empty;
            _addModalVisible = true;
        }

        /// <summary>
        /// 显示编辑对话框
        /// </summary>
        /// <param name="obj"></param>
        private void ShowEditModal(AnimationDto obj)
        {
            editModel.Id = obj.Id;
            editModel.Name = obj.Name;
            editModel.Url = obj.Url;
            editModel.Category = obj.Category;
            editModel.Region = obj.Region;
            editModel.Year = obj.Year;
            editModel.Director = obj.Director;
            editModel.Actors = obj.Actors;
            editModel.Img = obj.Img;
            editModel.Intro = obj.Intro;
            editModel.Comment = obj.Comment;
            _editModalvisible = true;
        }


        /// <summary>
        /// 删除单个
        /// </summary>
        /// <returns></returns>
        private async Task ConfirmDeleteAsync(string id)
        {
            var res = await HttpClient.DeleteAsync($"/api/animation/{id}");
            if (!res.IsSuccessStatusCode)
            {
                await MessageService.Error("操作失败", 2);
                return;
            }
            MessageService.Success("操作成功", 1.5);
            // 重载数据
            var resp = await HttpClient.GetAsync($"/api/animation/list?pageSize={_pageSize}&pageNum={_pageIndex}");
            var resData = JsonSerializer.Deserialize<TempData>(await resp.Content.ReadAsStringAsync(),
             new JsonSerializerOptions
             {
                 PropertyNameCaseInsensitive = true,
                 IncludeFields = true,
             });
            dataList = resData.Data;
        }


        /// <summary>
        /// 批量删除
        /// </summary>
        private async void BatchDelete()
        {
            if (selectedRows == null)
            {
                MessageService.Warning("请选择视频");
                return;
            }

            ModalService.Confirm(new ConfirmOptions()
            {
                Title = "确定进行批量删除吗?",
                OkType = "danger",
                OkText = "确定",
                CancelText = "取消",
                OnOk = async (e) =>
                {
                    var ids = selectedRows.Select(x => x.Id).ToList();
                    var res = await HttpClient.PostAsJsonAsync("/api/animation/batchDetele", ids);
                    if (!res.IsSuccessStatusCode)
                    {
                        MessageService.Error("操作失败", 2);
                        return;
                    }
                    MessageService.Success("操作成功", 1.5);
                    // 重载数据
                    var resp = await HttpClient.GetAsync($"/api/animation/list?pageSize={_pageSize}&pageNum={_pageIndex}");
                    var resData = JsonSerializer.Deserialize<TempData>(await resp.Content.ReadAsStringAsync(),
                     new JsonSerializerOptions
                     {
                         PropertyNameCaseInsensitive = true,
                         IncludeFields = true,
                     });
                    dataList = resData.Data;
                }
            });
        }


        /// <summary>
        /// 加载完毕事件
        /// </summary>
        /// <returns></returns>
        protected override async Task OnInitializedAsync()
        {
            HttpClient.DefaultRequestHeaders.Add("X-Req-Origin", "Admin");
            var resp = await HttpClient.GetAsync($"/api/animation/list?pageSize={_pageSize}&pageNum={_pageIndex}");
            var resData = JsonSerializer.Deserialize<TempData>(await resp.Content.ReadAsStringAsync(),
             new JsonSerializerOptions
             {
                 PropertyNameCaseInsensitive = true,
                 IncludeFields = true,
             });
            dataList = resData.Data;
            _total = resData.Total;
        }


        #region 添加表单相关操作

        private bool _addModalVisible = false;
        private AnimationForCreateDto addModel = new AnimationForCreateDto();
        private Form<AnimationForCreateDto> _addForm;


        /// <summary>
        /// OK按钮
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        private async Task HandleAddModalOkAsync(MouseEventArgs e)
        {
            if (!_addForm.Validate())
            {
                return;
            }
            var data = new AnimationForCreateDto
            {
                Name = addModel.Name,
                Url = addModel.Url,
                Category = addModel.Category,
                Region = addModel.Region,
                Year = addModel.Year,
                Actors = addModel.Actors,
                Director = addModel.Director,
                Img = addModel.Img,
                Intro = addModel.Intro,
                Comment = addModel.Comment,
            };
            var res = await HttpClient.PostAsJsonAsync<AnimationForCreateDto>("/api/animation", data);
            if (!res.IsSuccessStatusCode)
            {
                await MessageService.Error("操作失败", 2);
                return;
            }
            // 重载数据
            var resp = await HttpClient.GetAsync($"/api/animation/list?pageSize={_pageSize}&pageNum={_pageIndex}");
            var resData = JsonSerializer.Deserialize<TempData>(await resp.Content.ReadAsStringAsync(),
             new JsonSerializerOptions
             {
                 PropertyNameCaseInsensitive = true,
                 IncludeFields = true,
             });
            dataList = resData.Data;
            MessageService.Success("操作成功", 1.5);
            _addForm.Reset();
            _addModalVisible = false;
        }

        /// <summary>
        /// 取消按钮
        /// </summary>
        private void HandleAddModalCancel(MouseEventArgs e)
        {
            _addModalVisible = false;
        }

        /// <summary>
        /// 添加表单提交后关闭 modal
        /// </summary>
        private void OnAddFormFinish()
        {
            _addModalVisible = false;
        }

        /// <summary>
        /// add form submit err
        /// </summary>
        private void OnAddFormFinishFailed()
        {

        }
        #endregion



        #region 编辑表单相关操作

        bool _editModalvisible = false;
        private AnimationForUpdateDto editModel = new AnimationForUpdateDto();
        private Form<AnimationForUpdateDto> _editForm;

        /// <summary>
        /// 提交失败
        /// </summary>
        /// <param name="editContext"></param>
        private void OnEditFormFinishFailed(EditContext editContext)
        {
            //Console.WriteLine($"Failed:{JsonSerializer.Serialize(model)}");
        }


        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="e"></param>
        private void HandleEditModalCancel(MouseEventArgs e)
        {
            _editModalvisible = false;
        }



        /// <summary>
        /// 表单提交后关闭 modal
        /// </summary>
        /// <param name="editContext"></param>
        private void OnEditFormFinish(EditContext editContext)
        {
            _editModalvisible = false;
        }

        /// <summary>
        /// 点击modal的OK按钮提交表单
        /// </summary>
        /// <param name="e"></param>
        private async Task HandleEditModalOkAsync(MouseEventArgs e)
        {
            if (!_editForm.Validate())
            {
                return;
            }
            var data = new AnimationForUpdateDto
            {
                Id = editModel.Id,
                Name = editModel.Name,
                Url = editModel.Url,
                Category = editModel.Category,
                Region = editModel.Region,
                Year = editModel.Year,
                Actors = editModel.Actors,
                Director = editModel.Director,
                Img = editModel.Img,
                Intro = editModel.Intro,
                Comment = editModel.Comment,
            };
            var res = await HttpClient.PutAsJsonAsync<AnimationForUpdateDto>("/api/animation", data);
            if (!res.IsSuccessStatusCode)
            {
                await MessageService.Error("操作失败", 2);
                return;
            }
            // 重载数据
            var resp = await HttpClient.GetAsync($"/api/animation/list?pageSize={_pageSize}&pageNum={_pageIndex}");
            var resData = JsonSerializer.Deserialize<TempData>(await resp.Content.ReadAsStringAsync(),
             new JsonSerializerOptions
             {
                 PropertyNameCaseInsensitive = true,
                 IncludeFields = true,
             });
            dataList = resData.Data;
            MessageService.Success("操作成功", 1.5);
            _editForm.Reset();
            _editModalvisible = false;
        }

        #endregion
    }
}
